<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="发料单编号" prop="issueCode">
        <el-input
          v-model="queryParams.issueCode"
          placeholder="请输入发料单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="外协工单编码" prop="workorderCode">
        <el-input
          v-model="queryParams.workorderCode"
          placeholder="请输入外协工单编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供应商名称" prop="vendorName">
        <el-input
          v-model="queryParams.vendorName"
          placeholder="请输入供应商名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发料日期" prop="issueDate">
        <el-date-picker clearable
          v-model="queryParams.issueDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择发料日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mes:wm:outsourceissue:edit']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['mes:wm:outsourceissue:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['mes:wm:outsourceissue:edit']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="outsourceissueList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="发料单编号" align="center" prop="issueCode" >
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleView(scope.row)"
            v-hasPermi="['mes:wm:outsourceissue:list']"
          >{{scope.row.issueCode}}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="发料单名称" align="center" prop="issueName" />
      <el-table-column label="外协工单编码" align="center" prop="workorderCode" />
      <el-table-column label="供应商名称" align="center" prop="vendorName" />
      <el-table-column label="发料日期" align="center" prop="issueDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.issueDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单据状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_order_status" :value="scope.row.status"/>
        </template>
      </el-table-column>  
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-video-play"
            v-if="scope.row.status =='PREPARE'"
            @click="handleExecute(scope.row)"
            v-hasPermi="['mes:wm:outsourceissue:edit']"
          >执行发料</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-if="scope.row.status =='PREPARE'"
            v-hasPermi="['mes:wm:outsourceissue:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-if="scope.row.status =='PREPARE'"
            v-hasPermi="['mes:wm:outsourceissue:edit']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改外协发料单对话框 - 一体化界面 -->
    <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="open" width="1400px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!-- 发料单头信息 -->
        <el-card shadow="hover" class="mb20">
          <div slot="header" class="clearfix">
            <span class="card-title">发料单头信息</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="发料单编号" prop="issueCode">
                <el-input v-model="form.issueCode" :disabled="form.issueId?true:false" placeholder="请输入发料单编号" />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label-width="80">
                <el-switch 
                  :disabled="form.issueCode != null"
                  v-model="autoGenFlag"
                  active-color="#13ce66"
                  active-text="自动生成"
                  @change="handleAutoGenChange(autoGenFlag)" v-if="optType != 'view' && form.status =='PREPARE'">               
                </el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发料单名称" prop="issueName">
                <el-input v-model="form.issueName" placeholder="请输入发料单名称" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
               <el-form-item label="发料日期" prop="issueDate">
                <el-date-picker clearable
                  v-model="form.issueDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="请选择发料日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="发料仓库">
                <el-select v-model="form.warehouseId" placeholder="请选择发料仓库">
                  <el-option
                    v-for="item in warehouseOptions"
                    :key="item.pId"
                    :label="item.pName"
                    :value="item.pId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="单据状态" prop="status">
                <el-select v-model="form.status" disabled>
                  <el-option
                    v-for="dict in dict.type.mes_order_status"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>        
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="外协工单" prop="workorderCode">
                <el-input v-model="form.workorderCode" placeholder="请选择外协工单" >
                  <el-button slot="append" icon="el-icon-search" @click="handleWorkorderSelect"></el-button>
                </el-input>
                <WorkorderSelect ref="woSelect" v-if="showItemSelect" @closeSelect="closeSelect" :workorder="workorder" @onSelected="onWorkorderSelected"></WorkorderSelect>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="供应商" prop="vendorCode">
                <el-input v-model="form.vendorCode" readonly="readonly">
                  <el-button slot="append" @click="handleSelectVendor" icon="el-icon-search"></el-button>
                </el-input>
                <VendorSelect ref="vendorSelect" v-if="showItemSelect" @closeSelect="closeSelect" @onSelected="onVendorSelected" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="供应商名称" >
                <el-input v-model="form.vendorName" readonly placeholder="请选择外协工单" >               
                </el-input>
              </el-form-item>         
            </el-col>
          </el-row>        
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 物料明细信息 -->
        <el-card shadow="hover">
          <div slot="header" class="clearfix">
            <span class="card-title">物料明细信息</span>
            <el-button 
              v-if="optType != 'view' && form.status =='PREPARE'" 
              style="float: right; padding: 3px 0" 
              type="text" 
              icon="el-icon-plus"
              @click="handleAddMaterial"
            >添加物料</el-button>
          </div>
          
          <!-- 物料明细表格 -->
          <el-table v-loading="lineLoading" :data="materialList" @selection-change="handleMaterialSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="产品物料编码" width="120" align="center" prop="itemCode" />
            <el-table-column label="产品物料名称" width="150" align="center" prop="itemName" :show-overflow-tooltip="true"/>
            <el-table-column label="规格型号" align="center" prop="specification" :show-overflow-tooltip="true"/>
            <el-table-column label="单位" align="center" prop="unitOfMeasure" width="80" />
            <el-table-column label="领料数量" align="center" prop="quantityIssued" width="100" />
            <el-table-column label="批次号" align="center" prop="batchCode" width="120" />
            <el-table-column label="仓库名称" align="center" prop="warehouseName" width="120" />
            <el-table-column label="库区名称" align="center" prop="locationName" width="120" />
            <el-table-column label="库位名称" align="center" prop="areaName" width="120" />
            <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true"/>
            <el-table-column label="操作" align="center" v-if="optType != 'view'" width="120" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleEditMaterial(scope.row)"
                >修改</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDeleteMaterial(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 物料明细分页 -->
          <pagination
            v-show="materialTotal>0"
            :total="materialTotal"
            :page.sync="materialQueryParams.pageNum"
            :limit.sync="materialQueryParams.pageSize"
            @pagination="getMaterialList"
          />
        </el-card>
      </el-form>

      <!-- 物料选择对话框 -->
      <el-dialog title="选择物料" :visible.sync="materialDialogVisible" width="1000px" append-to-body>
        <el-form :model="materialQueryForm" :inline="true" label-width="100px">
          <el-form-item label="物料编码">
            <el-input v-model="materialQueryForm.itemCode" placeholder="请输入物料编码" clearable />
          </el-form-item>
          <el-form-item label="物料名称">
            <el-input v-model="materialQueryForm.itemName" placeholder="请输入物料名称" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchMaterial">搜索</el-button>
            <el-button @click="resetMaterialQuery">重置</el-button>
          </el-form-item>
        </el-form>
        
        <el-table :data="availableMaterialList" @selection-change="handleAvailableMaterialSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="物料编码" prop="itemCode" width="120" />
          <el-table-column label="物料名称" prop="itemName" width="150" />
          <el-table-column label="规格型号" prop="specification" />
          <el-table-column label="单位" prop="unitOfMeasure" width="80" />
          <el-table-column label="可用库存" prop="availableQuantity" width="100" />
          <el-table-column label="仓库" prop="warehouseName" width="120" />
        </el-table>
        
        <div slot="footer" class="dialog-footer">
          <el-button @click="materialDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmMaterialSelection">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 物料明细编辑对话框 -->
      <el-dialog title="编辑物料明细" :visible.sync="materialEditDialogVisible" width="800px" append-to-body>
        <el-form ref="materialForm" :model="materialForm" :rules="materialRules" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="产品物料编码" prop="itemCode">
                <el-input v-model="materialForm.itemCode" readonly placeholder="请选择产品物料编码" >
                  <el-button slot="append" @click="handleSelectStock" icon="el-icon-search"></el-button>
                </el-input>
                <StockSelect ref="stockSelect" v-if="showItemSelect" @closeSelect="closeSelect" :batchCode="materialForm.batchCode" :vendorId="form.vendorId" @onSelected="onStockSelected"></StockSelect>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="产品物料名称" prop="itemName">
                <el-input v-model="materialForm.itemName" readonly />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="领料数量" prop="quantityIssued">
                <el-input-number :min="0" :max="materialForm.quantityMax" v-model="materialForm.quantityIssued" placeholder="请输入领料数量" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="批次号" prop="batchCode">
                <el-input v-model="materialForm.batchCode" placeholder="请输入批次号" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="materialForm.remark" type="textarea" placeholder="请输入备注" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        
        <div slot="footer" class="dialog-footer">
          <el-button @click="materialEditDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitMaterialForm">确 定</el-button>
        </div>
      </el-dialog>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancel" v-if="optType =='view' || form.status !='PREPARE' ">返回</el-button>     
        <el-button type="primary" @click="submitForm" v-if="form.status =='PREPARE' && optType !='view' ">保 存</el-button>           
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOutsourceissue, getOutsourceissue, delOutsourceissue, addOutsourceissue, updateOutsourceissue, execute } from "@/api/mes/wm/outsourceissue";
import { listOutsourceissueline, addOutsourceissueline, updateOutsourceissueline, delOutsourceissueline } from "@/api/mes/wm/outsourceissueline";
import { listMdItem } from "@/api/mes/md/mdItem";
import WorkorderSelect from "@/components/workorderSelect/single.vue"
import VendorSelect from "@/components/vendorSelect/single.vue";
import StockSelect from "@/components/stockSelect/single.vue";
import {getTreeList} from "@/api/mes/wm/warehouse"
import {genCode} from "@/api/system/autocode/rule"
import Issueline from "./line.vue";
export default {
  name: "Outsourceissue",
  dicts: ['mes_order_status'],
  components: {Issueline,WorkorderSelect,VendorSelect,StockSelect},
  data() {
    return {
      autoGenFlag:false,
      optType: undefined,
      warehouseInfo:[],
      warehouseOptions:[],
      warehouseProps:{
        multiple: false,
        value: 'pId',
        label: 'pName',
      },
      // 遮罩层
      loading: true,
      lineLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 外协领料单头表格数据
      outsourceissueList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //工单弹出框结果过滤参数
      workorder: { workorderType: 'OUTSOURCE'},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        issueCode: null,        
        issueName: null,        
        workorderId: null,        
        workorderCode: null,        
        vendorId: null,        
        vendorCode: null,        
        vendorName: null,        
        vendorNick: null,        
        warehouseId: null,        
        warehouseCode: null,        
        warehouseName: null,        
        locationId: null,        
        locationCode: null,        
        locationName: null,        
        areaId: null,        
        areaCode: null,        
        areaName: null,        
        issueDate: null,        
        status: null,      
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        issueCode: [
          { required: true, message: "发料单编号不能为空", trigger: "blur" }
        ],        
        issueName: [
          { required: true, message: "发料单名称不能为空", trigger: "blur" }
        ],
        workorderCode: [
          { required: true, message: "请选择外协工单", trigger: "blur" }
        ]
      },
      showItemSelect: true, // 是否显示物料选择
      
      // 物料明细相关
      materialList: [],
      materialTotal: 0,
      materialQueryParams: {
        pageNum: 1,
        pageSize: 10,
        issueId: null
      },
      materialDialogVisible: false,
      materialEditDialogVisible: false,
      materialForm: {},
      materialRules: {
        itemCode: [
          { required: true, message: "请选择产品物料编码", trigger: "blur" }
        ],
        quantityIssued: [
          { required: true, message: "请输入领料数量", trigger: "blur" }
        ]
      },
      availableMaterialList: [],
      selectedMaterials: [],
      materialQueryForm: {
        itemCode: '',
        itemName: ''
      }
    };
  },
  created() {
    this.getList();
    this.getWarehouseList();
  },
  methods: {
    /** 查询外协领料单头列表 */
    getList() {
      this.loading = true;
      listOutsourceissue(this.queryParams).then(response => {
        this.outsourceissueList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getWarehouseList(){
      getTreeList().then( response =>{        
        if(response.data){
          this.warehouseOptions = response.data.filter((el) =>{
              return el.warehouseCode.indexOf('VIR') == -1;
          });;
        }
        this.warehouseOptions.map(w =>{
          w.children.map(l =>{
                  let lstr =JSON.stringify(l.children).replace(/locationId/g,'lId').replace(/areaId/g, 'pId').replace(/areaName/g,'pName');                  
                  l.children = JSON.parse(lstr);
          });
            
          let wstr = JSON.stringify(w.children).replace(/warehouseId/g,'wId').replace(/locationId/g, 'pId').replace(/locationName/g,'pName');  
          w.children =  JSON.parse(wstr); 

        });
        let ostr=JSON.stringify(this.warehouseOptions).replace(/warehouseId/g,'pId').replace(/warehouseName/g, 'pName');
        this.warehouseOptions = JSON.parse(ostr);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        issueId: null,        
        issueCode: null,        
        issueName: null,        
        workorderId: null,        
        workorderCode: null,        
        vendorId: null,        
        vendorCode: null,        
        vendorName: null,        
        vendorNick: null,        
        warehouseId: null,        
        warehouseCode: null,        
        warehouseName: null,        
        locationId: null,        
        locationCode: null,        
        locationName: null,        
        areaId: null,        
        areaCode: null,        
        areaName: null,        
        issueDate: new Date(),        
        status: "PREPARE",        
        remark: null,        
        attr1: null,        
        attr2: null,        
        attr3: null,        
        attr4: null,        
        createBy: null,        
        createTime: null,        
        updateBy: null,        
        updateTime: null      
      };
      this.autoGenFlag = false;
      this.materialList = [];
      this.materialTotal = 0;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.issueId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加外协发料单头";
      this.optType = "add";
      // 这里是新增，这个新增发料单编号可以直接生成编码
      this.autoGenFlag = true;
      genCode('OUTSOURCE_ISSUE_CODE').then(response => {
        this.form.issueCode = response;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const issueId = row.issueId || this.ids
      getOutsourceissue(issueId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改外协发料单头";
        this.optType = "edit";
        // 加载物料明细
        this.getMaterialList();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.issueId != null) {
            updateOutsourceissue(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOutsourceissue(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const issueIds = row.issueId || this.ids;
      this.$modal.confirm('是否确认删除外协发料单头编号为"' + issueIds + '"的数据项？').then(function() {
        return delOutsourceissue(issueIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 查询明细按钮操作
    handleView(row){
      this.reset();
      const issueIds = row.issueId
      getOutsourceissue(issueIds).then(response => {
        this.form = response.data;
        this.warehouseInfo[0] = response.data.warehouseId;    
        this.warehouseInfo[1] = response.data.locationId;    
        this.warehouseInfo[2] = response.data.areaId; 
        this.open = true;
        this.title = "查看外协发料单信息";
        this.optType = "view";
        // 加载物料明细
        this.getMaterialList();
      });
    },
    //执行发料
    handleExecute(row){
      const issueIds = row.issueId || this.ids;
      this.$modal.confirm('确认执行发料？').then(function() {
        return execute(issueIds)
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("出库成功");
      }).catch(() => {});
    },
    //选择生产工单
    handleWorkorderSelect(){
      this.$refs.woSelect.showFlag = true;
    },
    onWorkorderSelected(row){
      // debugger
      if(row != undefined && row != null){
        this.form.workorderId = row.workorderId;
        this.form.workorderCode = row.workorderCode;
        this.form.workorderName = row.workorderName;
        this.form.vendorId = row.vendorId;
        this.form.vendorCode = row.vendorCode;
        this.form.vendorName = row.vendorName;
        this.closeSelect();
      }
    },
    //供应商选择
    handleSelectVendor(){
      this.$refs.vendorSelect.showFlag = true;
    },
    //供应商选择弹出框
    onVendorSelected(obj){
        if(obj != undefined && obj != null){
          this.form.vendorId = obj.vendorId;
          this.form.vendorCode = obj.vendorCode;
          this.form.vendorName = obj.vendorName;
          this.form.vendorNick = obj.vendorNick;
          this.closeSelect();
        }
    },
    //自动生成编码
    handleAutoGenChange(autoGenFlag){
      if(autoGenFlag){
        genCode('OUTSOURCE_ISSUE_CODE').then(response =>{
          this.form.issueCode = response;
        });
      }else{
        this.form.issueCode = null;
      }
    },
    closeSelect(){
      this.showItemSelect = false;
      setTimeout(()=>{
        this.showItemSelect = true;
      }, 200)
    },

    // 物料明细相关方法
    getMaterialList() {
      if (!this.form.issueId) return;
      this.lineLoading = true;
      this.materialQueryParams.issueId = this.form.issueId;
      listOutsourceissueline(this.materialQueryParams).then(response => {
        this.materialList = response.rows;
        this.materialTotal = response.total;
        this.lineLoading = false;
      }).catch(() => {
        this.lineLoading = false;
      });
    },
    
    handleAddMaterial() {
      this.materialDialogVisible = true;
      this.searchMaterial();
    },
    
    handleEditMaterial(row) {
      this.materialForm = { ...row };
      this.materialEditDialogVisible = true;
    },
    
    handleDeleteMaterial(row) {
      this.$modal.confirm('确认删除该物料明细？').then(() => {
        return delOutsourceissueline(row.lineId);
      }).then(() => {
        this.$modal.msgSuccess("删除成功");
        this.getMaterialList();
      }).catch(() => {});
    },
    
    handleMaterialSelectionChange(selection) {
      this.selectedMaterials = selection;
    },
    
    searchMaterial() {
      const query = {
        pageNum: 1,
        pageSize: 100,
        itemCode: this.materialQueryForm.itemCode || undefined,
        itemName: this.materialQueryForm.itemName || undefined
      };
      
      listMdItem(query).then(response => {
        this.availableMaterialList = response.rows.map(item => ({
          itemCode: item.itemCode,
          itemName: item.itemName,
          specification: item.specification,
          unitOfMeasure: item.unitOfMeasure,
          availableQuantity: 0, // 这里需要调用库存API获取实际可用数量
          warehouseName: '主仓库' // 这里需要根据实际情况设置
        }));
      }).catch(() => {
        this.availableMaterialList = [];
      });
    },
    
    resetMaterialQuery() {
      this.materialQueryForm = {
        itemCode: '',
        itemName: ''
      };
      this.searchMaterial();
    },
    
    handleAvailableMaterialSelectionChange(selection) {
      this.selectedMaterials = selection;
    },
    
    confirmMaterialSelection() {
      if (this.selectedMaterials.length === 0) {
        this.$modal.msgWarning("请选择物料");
        return;
      }
      
      // 将选中的物料添加到明细列表
      this.selectedMaterials.forEach(material => {
        const materialLine = {
          issueId: this.form.issueId,
          itemCode: material.itemCode,
          itemName: material.itemName,
          specification: material.specification,
          unitOfMeasure: material.unitOfMeasure,
          quantityIssued: 1,
          batchCode: '',
          warehouseName: material.warehouseName,
          locationName: '',
          areaName: '',
          remark: ''
        };
        
        // 直接调用API创建物料明细
        addOutsourceissueline(materialLine).then(response => {
          this.$modal.msgSuccess("物料添加成功");
          this.getMaterialList();
        });
      });
      
      this.materialDialogVisible = false;
    },
    
    submitMaterialForm() {
      this.$refs.materialForm.validate(valid => {
        if (valid) {
          // 设置发料单ID
          this.materialForm.issueId = this.form.issueId;
          
          if (this.materialForm.lineId) {
            // 更新
            updateOutsourceissueline(this.materialForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.materialEditDialogVisible = false;
              this.materialForm = {};
              this.getMaterialList();
            });
          } else {
            // 新增
            addOutsourceissueline(this.materialForm).then(response => {
              this.$modal.msgSuccess("添加成功");
              this.materialEditDialogVisible = false;
              this.materialForm = {};
              this.getMaterialList();
            });
          }
        }
      });
    },
    
    handleSelectStock() {
      this.$refs.stockSelect.showFlag = true;
    },
    
    onStockSelected(stock) {
      if (stock) {
        this.materialForm.itemCode = stock.itemCode;
        this.materialForm.itemName = stock.itemName;
        this.materialForm.specification = stock.specification;
        this.materialForm.unitOfMeasure = stock.unitOfMeasure;
        this.materialForm.quantityMax = stock.availableQuantity;
        this.closeSelect();
      }
    }
  }
};
</script>

<style scoped>
.mb20 {
  margin-bottom: 20px;
}

.card-title {
  font-weight: bold;
  color: #303133;
}

.clearfix::after {
  content: "";
  display: table;
  clear: both;
}
</style>
